package com.kavenka.zhufengfm.app.tasks.discover;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import com.kavenka.zhufengfm.app.cache.FileCache;
import com.kavenka.zhufengfm.app.cache.ImageCache;
import com.kavenka.zhufengfm.app.http.HttpUtil;
import com.kavenka.zhufengfm.app.utils.ScaleBitmapUtil;

import java.lang.ref.WeakReference;

/**
 * Created by kavenka on 2015/9/27 0027.
 */
public class ImageLoadTask extends AsyncTask<String,Void,Bitmap> {
    /**
     * 使用弱饮用包裹ImageView，支持GC，释放之后不会再设置图片
     */
    private WeakReference<View> imageViewReference;
    private String url;
    private Context context;

    public ImageLoadTask(ImageView imageView,Context context) {
        imageViewReference=new WeakReference<View>(imageView);
        this.context=context;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap ret=null;
        url = params[0];
        if (params != null&&params.length>0) {
            //1.先从内存缓存查找
            ImageCache imageCache = ImageCache.getInstance();
            Bitmap bitmap = imageCache.get(url);
            //2.如果内存缓存中没有，就看文件缓存
            if (bitmap == null) {
                byte[] bytes = FileCache.createInstance(context).load(url);
                //3.如果文件缓存不存在，则从网络中下载
                if (bytes == null) {
                    bytes= HttpUtil.doGet(url);
                    //TODO 没有执行到这里，bug
                    FileCache.getInstance().save(url,bytes);
                    //3.1如果文件缓存存在，解码字节数组,缩小图片大小
                }else {
                    ret= ScaleBitmapUtil.loadScaleBitmap(bytes,256,256);
                    bytes=null;
                    imageCache.put(url,ret);
                }
            }
            //2.1 如果内存缓存存在
            else {
                ret=bitmap;
            }
        }
        return ret;
    }

    /**
     * 适配器异步任务的处理
     * @param bitmap
     */
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            View view = imageViewReference.get();
            if (view != null) {
                Object tag = view.getTag();
                boolean match=true;
                if (tag != null) {
                    if (tag instanceof String){
                        String str= (String) tag;
                        match = str.equals(url);
                    }
                }
                if (match){
                    if (view instanceof ImageView){
                        ((ImageView) view).setImageBitmap(bitmap);
                    }else {
                        view.setBackgroundDrawable(new BitmapDrawable(bitmap));
                    }
                }
            }
        }
    }
}
